package com.soboot.datasource.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.soboot.base.constant.BaseConstant;
import com.soboot.base.util.SecurityUtil;
import com.soboot.datasource.injector.BaseLogicSqlInjector;
import com.soboot.datasource.intercptor.DataScopeInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Author:
 * @createTime: 2022年09月19日 15:28:31
 * @version:
 * @Description:
 * @Copyright:
 */
@Configuration
public class MybatisConfig implements MetaObjectHandler {

    /**
     * 分页插件
     *
     * @return PaginationInterceptor
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    /**
     * 数据权限插件
     *
     * @return DataScopeInterceptor
     */
    @Bean
    public DataScopeInterceptor dataScopeInterceptor() {
        return new DataScopeInterceptor();
    }

    /**
     * 自定义 SqlInjector
     * 里面包含自定义的全局方法
     */
    @Bean
    public BaseLogicSqlInjector baseLogicSqlInjector() {
        return new BaseLogicSqlInjector();
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime",  new Date(),metaObject);
        //this.setFieldValByName("updateTime",new Date(),metaObject);
        this.strictInsertFill(metaObject, "status", String.class, BaseConstant.EnableState.ENABLE.getKey());
        this.strictInsertFill(metaObject, "createBy", String.class, SecurityUtil.getUserId());
        this.strictInsertFill(metaObject, "updateBy", String.class, SecurityUtil.getUserId());
        boolean bolCreateDept = metaObject.hasSetter("createDept");
        if (bolCreateDept) {
            this.strictInsertFill(metaObject, "createDept", String.class, SecurityUtil.getUserDeptId());
        }
        boolean bolFlowStatus = metaObject.hasSetter("flowStatus");
        if (bolFlowStatus) {
            this.strictInsertFill(metaObject, "flowStatus", String.class, BaseConstant.AuditState.WAIT.getKey());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.setFieldValByName("updateTime",new Date(),metaObject);
        this.strictUpdateFill(metaObject, "updateBy", String.class, SecurityUtil.getUserId());
    }
}
